#include "stm32f2xx.h"
#include "string.h" //for memcpy
#include "can_transmit_queue.h"

/**
 * @brief 初始化队列
 */
void init_queue(struct can_transmit_queue * queue_pointer )
{
	queue_pointer->number = 0;
	queue_pointer->front = 0;
	queue_pointer->rear = 0;
	queue_pointer->operation_flag = IDLE;
}
/**
 * @brief 判断队列是否为空
 * @retval  
 * -0 不为空
 * -1 空
 */
int is_queue_empty(const struct can_transmit_queue* queue_pointer)
{
	return (queue_pointer->front == queue_pointer->rear);
}


/**
 * @brief 把元素插入队列尾部
 * @retval  
 * -0 失败，队列满 
 * -1成功
 */
int  insert_queue(struct can_transmit_queue* queue_pointer, CanTxMsg* p_data)
{
	int tmp = 0;
	if(queue_pointer->operation_flag == IDLE)
	{
		queue_pointer->operation_flag = INSERTING;
		/* 队列已经满了 */
		if((QUEUE_LEN-1)==queue_pointer->number)
		{	
			queue_pointer->operation_flag = IDLE;
			/* 队列已经满了 */
			return 0;
		}
		else
		{
			queue_pointer->number++;
			memcpy(queue_pointer->data + queue_pointer->rear, p_data, sizeof(CanTxMsg));
			//确保原子操作
			tmp = queue_pointer->rear + 1;
			queue_pointer->rear = tmp%QUEUE_LEN;
			queue_pointer->operation_flag = IDLE;
			return 1;
		}

	}
	else
	{
		return 0;
	}
}

/**
 * @brief  获取队列的首元素
 * @retval  
 * -0 失败，队列为空  
 * -1成功
 */
int  get_queue_front(const struct can_transmit_queue* queue_pointer,CanTxMsg* data)
{
	/*如果队列非空*/
	if(queue_pointer->operation_flag == IDLE)
	{
		if (is_queue_empty(queue_pointer))
		{
			return 0;	
		}
		else
		{
			memcpy(data, queue_pointer->data + queue_pointer->front, sizeof(CanTxMsg));
			return 1;
		}
	}
	else
	{
		return 0;
	}
}

/**
 * @brief  删除队列队首元素
 * @retval  
 * -0 失败，队列为空  
 * -1成功
 */
int delet_queue_front(struct can_transmit_queue* queue_pointer)
{

	if(queue_pointer->operation_flag == IDLE)
	{
		int tmp = 0;
		if(is_queue_empty(queue_pointer))
		{
			return 0;
		}
		else
		{
			queue_pointer->number--;
			tmp = queue_pointer->front + 1;
			queue_pointer->front= tmp%QUEUE_LEN;
			return 1;
		}
	}
	else
	{
		return 0;
	}
}
